#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static long long
datetounix(long long year, int mon, int day, int hour, int min, int sec)
{
	static const int secs_through_month[] = {
		0, 31 * 86400, 59 * 86400, 90 * 86400,
		120 * 86400, 151 * 86400, 181 * 86400, 212 * 86400,
		243 * 86400, 273 * 86400, 304 * 86400, 334 * 86400 };
	int is_leap = 0, cycles, centuries = 0, leaps = 0, rem;
	long long t;

	if (year - 2ULL <= 136) {
		leaps = (year - 68) >> 2;
		if (!((year - 68) & 3)) {
			leaps--;
			is_leap = 1;
		} else {
			is_leap = 0;
		}
		t = 31536000 * (year - 70) + 86400 * leaps;
	} else {
		cycles = (year - 100) / 400;
		rem = (year - 100) % 400;
		if (rem < 0) {
			cycles--;
			rem += 400;
		}
		if (!rem) {
			is_leap = 1;
		} else {
			if (rem >= 300)
				centuries = 3, rem -= 300;
			else if (rem >= 200)
				centuries = 2, rem -= 200;
			else if (rem >= 100)
				centuries = 1, rem -= 100;
			if (rem) {
				leaps = rem / 4U;
				rem %= 4U;
				is_leap = !rem;
			}
		}
		leaps += 97 * cycles + 24 * centuries - is_leap;
		t = (year - 100) * 31536000LL + leaps * 86400LL + 946684800 + 86400;
	}
	t += secs_through_month[mon];
	if (is_leap && mon >= 2)
		t += 86400;
	t += 86400LL * (day - 1);
	t += 3600LL * hour;
	t += 60LL * min;
	t += sec;

	return t;
}


long long 
*dateparse(char *datestring)
{
	/* parses datestring into year, month, and date */
	char *datestr = datestring;
	int i;
	long long *copy = malloc(sizeof(long long) * 3);
	long long dateinfo[3];	

	for(i = 0; i < 3 && (dateinfo[i] = atoi(strsep(&datestr, "-"))) != NULL; i++)
		;//printf("dateinfo[%d]: %lld\n", i, dateinfo[i]);
	memcpy(copy, dateinfo, 3 * sizeof(long long));
	return copy;
		
}

int 
lineisgood(char *line)
{
	return line[0] != '#' && line[0] != '\0';
}

int 
main(int argc, char *argv[])
{
	/* Take input: change date format into unix timestamp, then switch orders of 2nd and 3rd fields  
	 Since I'm parsing and repackaging the data, I'll read in the data and then print it out */

	int i;
	char *fields[3];
	char line[2048];
	FILE *stream;

	if(!(stream = fopen(argv[1], "r"))) {
		stream = stdin;
	}

	while (fgets(line, sizeof(line), stream)) {
		line[strcspn(line, "\n")] = '\0';
		char *st = line;
		for(i = 0; i < 3 && (fields[i] = strsep(&st, "\t")) != NULL; i++)
			;
		
		if(lineisgood(line)) {
			char *datestring = fields[0];
			long long *dateinfo = dateparse(datestring);
			long long timestamp = datetounix(dateinfo[0] - 1900, (int)dateinfo[1] - 1, (int)dateinfo[2], -20, 0, 0);
			free(dateinfo);
			printf("%lld\t%s\t%s\n", timestamp, fields[2], fields[1]);
		}
	}
}
